Few doubts regarding Bitmaps , Images & `using` blocks

Posted by imageWorker on Stack Overflow See other posts from Stack Overflow or by imageWorker
Published on 2010-04-01T13:06:12Z Indexed on 2010/04/01 14:13 UTC
Read the original article Hit count: 252

Filed under:
|

I caught up in this problem.

http://stackoverflow.com/questions/2559826/garbage-collector-not-doing-its-job-memory-consumption-1-5gb-outofmemory-exc

I feel that there is something wrong in my understanding. Please clarify these things.

  1. Destructor & IDisposable.Dispose are two methods for freeing resources that are not not under the control of .NET. Which means, everything except memory. right?
  2. using blocks are just better way of calling IDisposable.Dispose() method of an object.

This is the main code I'm referring to.

class someclass
{
    static someMethod(Bitmap img)
    {
        Bitmap bmp = new Bitmap(img); //statement1
        // some code here and return
    }
}

here is class I'm using for testing:

class someotherClass
{
    public static voide Main()
    {
        foreach (string imagePath in imagePathsArray)
        {
            using (Bitmap img1 = new Bitmap(imagePath))
            {
                someclass.someMethod(img1);
                // does some more processing on `img1`
            }
        }
    }
}

Is there any memory leak with statement1?

Question1: If each image size is say 10MB. Then does this bmp object occupy atleast 10MB? What I mean is, will it make completely new copy of entire image? or just refer to it?

Question2:should I or should I not put the statement1 in using block?

My Argument: We should not. Because using is not for freeing memory but for freeing the resources (file handle in this case). If I use it in using block. It closes file handle here encapsulated by this bmp object. It means we are also closing filehandle for the caller's img1 object. Which is not correct?

As of the memory leak. No there is no scope of memory leak here. Because reference bmp is destroyed when this method is returned. Which leaves memory it refered without any pointer. So, its garbage collected. Am I right?

Edit:

class someclass
{
    static Bitmap someMethod(Bitmap img)
    {
       Bitmap bmp = new Bitmap(img); //can I use `using` block on this enclosing `return bmp`; ???
        // do some processing on bmp here
       return bmp;
    }
}

© Stack Overflow or respective owner

Related posts about c#

Related posts about .NET